package com.itheima.filter;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.RedirectToGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @desc
 * @author:ivan.liu
 */
@Component
public class TokenGatewayFilterFactory  extends AbstractGatewayFilterFactory<TokenGatewayFilterFactory.Config> {

    public static final String NAME_KEY = "name";
    public static final String VALUE_KEY = "value";

    public TokenGatewayFilterFactory() {
        super(TokenGatewayFilterFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY, VALUE_KEY);
    }


    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                List<String> tokenList = exchange.getRequest().getHeaders().get(config.name);
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();
                if(tokenList==null||tokenList.size()!=1){
                    response.setStatusCode(HttpStatus.BAD_GATEWAY);
                    return response.setComplete();
                }
                String token = tokenList.get(0);
                if (!token.equals("lywivan")){
                    response.setStatusCode(HttpStatus.BAD_GATEWAY);
                    return response.setComplete();
                }
                //request.getHeaders().remove("token");
                request.mutate().header("Token","lllllll");
                return chain.filter(exchange);
            }
        };
    }

    @Data
    public static class Config {
        String name;
        String value;
    }
}
